package user.zc.api;

import user.zc.controller.impl.ConnectCollector;
import user.zc.util.R;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class APIProxyFactory {

    static class ApiProxy<T> implements InvocationHandler {

        private T target ;
        public ApiProxy(T target){
            this.target = target;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String methodName = method.getName();
            Method targetMethod = target.getClass().getDeclaredMethod(methodName);
            if(targetMethod!=null){
                return R.success(()-> {
                    try {
                        return method.invoke(target, args);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return R.failure(e.getMessage());
                    }
                }); //调用目标对象的方法
            }
            return R.failure("方法不存在");
        }
    }

    public static <T,R extends T> T getProxy(InvocationHandler inter, R target){
        return  (T)Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                inter);
    }

    public static IConnectionApi getConnectionProxy(){
        ConnectCollector connectCollector = new ConnectCollector();
        return (IConnectionApi) getProxy(new ApiProxy(connectCollector),connectCollector);
    }
}
